package com.woniu.execption;

import cn.hutool.json.JSONUtil;
import com.woniu.utils.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GatewayGloableException implements ErrorWebExceptionHandler {

    //在访问验证里应该抛异常，而gateway路由并不是一个web项目，不能被common里面的全局异常处理器捕获
    //所以要创建一个自己的异常捕获类


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ex.printStackTrace();
        Result<?> result = null;
        if(ex instanceof RebornException){
            //捕获到的是自定义异常
            RebornException e = (RebornException)ex;
            result = Result.newInstance(null).setCode(e.getCode()).setMessage(e.getMessage());
        }else {
            //非自定义异常
            result = Result.newInstance(null).setCode(500).setMessage("系统异常");
        }

        String json = JSONUtil.parse(result).toString();
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
